package com.dek.grpc.header;

import com.dek.grpc.dto.HelloReply;
import com.dek.grpc.dto.HelloRequest;
import com.dek.grpc.helloworld.HelloWorldServer;
import com.dek.grpc.service.HelloServiceGrpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.ServerInterceptors;
import io.grpc.stub.StreamObserver;

import java.io.IOException;
import java.util.logging.Logger;

public class CustomHeaderServer {
    private static final Logger logger = Logger.getLogger(CustomHeaderServer.class.getName());

    private Server server;
    private static final int PORT = 50051;

    private void start() throws IOException {
        server = ServerBuilder.forPort(PORT)
                .addService(ServerInterceptors.intercept(new HelloWorldImpl(),
                        new HeaderServerInterceptor())).build().start();
        logger.info("Server started, listening on " + PORT);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                // Use stderr here since the logger may have been reset by its JVM shutdown hook.
                System.err.println("*** shutting down gRPC server since JVM is shutting down");
                CustomHeaderServer.this.stop();
                System.err.println("*** server shut down");
            }
        });
    }

    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }


    public static void main(String[] args) throws IOException, InterruptedException {
        final CustomHeaderServer server = new CustomHeaderServer();
        server.start();
        server.blockUntilShutdown();
    }


    private static class HelloWorldImpl extends HelloServiceGrpc.HelloServiceImplBase {

        @Override
        public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
            HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }


}
